package org.celery.mobile.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.celery.common.utils.MemberTokenUtil;
import org.celery.core.secure.AuthMember;
import org.celery.core.secure.MemberAuthInfo;
import org.celery.core.secure.utils.AuthUtil;
import org.celery.mobile.entity.WxUserInfo;
import org.celery.modules.member.entity.Member;
import org.celery.modules.member.service.IMemberService;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.web.bind.annotation.*;

/**
 * Create on 2021-11-22
 *
 * @author Celery <1031868928@qq.com>
 */
@RestController
@AllArgsConstructor
@RequestMapping("/mobile/member")
public class MobileMemberController {

    private final IMemberService memberService;

    @PostMapping(value = "sign-up")
    public R<Member> signUp(@RequestBody WxUserInfo wxUserInfo) {
        Member member = new Member() {{
            setAvatar(wxUserInfo.getAvatarUrl());
            setNickname(wxUserInfo.getNickName());
            setWxMaOpenId(wxUserInfo.getOpenId());
            setPhone(wxUserInfo.getTelephone());
            setSex(wxUserInfo.getGender());
            setBirthday(DateUtil.fromDate(wxUserInfo.getBirthday()));
        }};
        if (!memberService.save(member)) {
            throw new ServiceException("注册失败");
        }
        return R.data(memberService.getOne(Wrappers.<Member>lambdaQuery()
                .eq(Member::getWxMaOpenId, wxUserInfo.getOpenId())
        ));
    }

    @PostMapping(value = "check-unique-phone")
    public R<Boolean> checkUniquePhone(@RequestParam String phone) {
        Member member = memberService.getOne(Wrappers.<Member>lambdaQuery()
                .eq(Member::getPhone, phone));
        return R.status(Func.isNotEmpty(member));
    }

    @PostMapping(value = "login")
    public R<MemberAuthInfo> login(@RequestParam String openId) {
        Member member = memberService.getOne(Wrappers.<Member>lambdaQuery()
                .eq(Member::getWxMaOpenId, openId));

        if (Func.isEmpty(member)) {
            return R.data(null);
        }

        return R.data(MemberTokenUtil.createAuthInfo(member));
    }

    @PostMapping(value = "update-profile")
    public R<Boolean> updateProfile(@RequestBody Member member) {
        AuthMember authMember = AuthUtil.getMember();
        member.setId(authMember.getUserId());
        return R.status(memberService.updateById(member));
    }
}
